package cn.hznc.configuration;

import cn.hznc.domain.entity.MqttProp;
import cn.nerc.nclink.core.communication.DeviceClient3;
import cn.nerc.nclink.core.general.InvalidException;
import cn.nerc.nclink.core.message.QueryRequestItem;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeoutException;

/**
 * @Author：Administrator
 * @Date：2023/6/6 17:01
 */
@Component
@EnableConfigurationProperties(MqttProp.class)
@Slf4j
public class MqttHelper{

    @Autowired
    private MqttProp mqttProp;

    private ConcurrentHashMap<String, DeviceClient3> _Client3Map;



    //新版
    private DeviceClient3 Connect3Device(String sn) throws InvalidException, MqttException {
        if (this._Client3Map == null) {
            _Client3Map = new ConcurrentHashMap<>();
        }
        DeviceClient3 ret = _Client3Map.get(sn);
        if (ret != null) {
            if (!ret.isConnected())
                if (!ret.connect()) {
                    ret = null;
                }

        }
        if (ret == null) {
            DeviceClient3 deviceClient3 = new DeviceClient3(sn, mqttProp.getHostUrl(), UUID.randomUUID().toString(), mqttProp.getUsername() ,
                    mqttProp.getPassword());
            if (deviceClient3 != null || !deviceClient3.isConnected()) {
                deviceClient3.connect();
            }
            ret = deviceClient3;
            _Client3Map.put(sn, deviceClient3);
        }
        return ret;
    }

    public List<Object> getCurrentGFileLineNumber(String sn) throws MqttException, InvalidException, TimeoutException, InterruptedException {
        //DeviceClient2 deviceClient = ConnectDevice(sn);
        DeviceClient3 deviceClient = Connect3Device(sn);
        String id = deviceClient.getIdOf("/NC_LINK_ROOT/MACHINE/CONTROLLER/LINE_NUMBER");
        return deviceClient.easyQuery(2000, new QueryRequestItem.Builder().id(id).build());
    }

}
